import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useSettingsStore } from './settingsStore'

export const useTaskStore = defineStore('tasks', () => {
  const settingsStore = useSettingsStore()
  
  const tasks = ref([])
  const currentTask = ref(null)
  const downloadSpeeds = ref(new Map()) // 存储每个任务的下载速度

  // 计算属性 - 按时间倒序排列
  const activeTasks = computed(() => 
    tasks.value
      .filter(task => ['downloading', 'merging', 'parsing'].includes(task.status))
      .sort((a, b) => (b.startTime || 0) - (a.startTime || 0))
  )

  const completedTasks = computed(() => 
    tasks.value
      .filter(task => task.status === 'completed')
      .sort((a, b) => (b.startTime || 0) - (a.startTime || 0))
  )

  const failedTasks = computed(() => 
    tasks.value
      .filter(task => task.status === 'error')
      .sort((a, b) => (b.startTime || 0) - (a.startTime || 0))
  )

  const pausedTasks = computed(() => 
    tasks.value
      .filter(task => task.status === 'paused')
      .sort((a, b) => (b.startTime || 0) - (a.startTime || 0))
  )

  const pendingTasks = computed(() => 
    tasks.value
      .filter(task => task.status === 'pending')
      .sort((a, b) => (b.startTime || 0) - (a.startTime || 0))
  )

  // 从localStorage加载任务
  const loadTasksFromStorage = () => {
    try {
      const savedTasks = localStorage.getItem('m3u8-downloader-tasks')
      if (savedTasks) {
        tasks.value = JSON.parse(savedTasks)
      }
    } catch (error) {
      console.error('Failed to load tasks from storage:', error)
    }
  }

  // 保存任务到localStorage
  const saveTasksToStorage = () => {
    try {
      localStorage.setItem('m3u8-downloader-tasks', JSON.stringify(tasks.value))
    } catch (error) {
      console.error('Failed to save tasks to storage:', error)
    }
  }

  // 格式化文件大小
  const formatFileSize = (bytes) => {
    if (!bytes || bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 格式化下载速度
  const formatDownloadSpeed = (bytesPerSecond) => {
    if (!bytesPerSecond || bytesPerSecond === 0) return '0 B/s'
    const k = 1024
    const sizes = ['B/s', 'KB/s', 'MB/s', 'GB/s']
    const i = Math.floor(Math.log(bytesPerSecond) / Math.log(k))
    return parseFloat((bytesPerSecond / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 计算进度百分比（整数）
  const calculateProgress = (downloadedSize, totalSize, downloadedSegments, totalSegments) => {
    // 优先使用分片进度，因为分片进度更准确
    if (downloadedSegments && totalSegments && totalSegments > 0) {
      const segmentProgress = Math.floor((downloadedSegments / totalSegments) * 100)
      console.log(`Progress calculated from segments: ${downloadedSegments}/${totalSegments} = ${segmentProgress}%`)
      return segmentProgress
    }
    
    // 如果没有分片信息，使用文件大小计算
    if (downloadedSize && totalSize && totalSize > 0) {
      const sizeProgress = Math.floor((downloadedSize / totalSize) * 100)
      console.log(`Progress calculated from size: ${downloadedSize}/${totalSize} = ${sizeProgress}%`)
      return sizeProgress
    }
    
    console.log('No progress data available, returning 0%')
    return 0
  }

  // 计算文件总大小（根据分片信息）
  const calculateTotalSize = (segments, totalSegments, estimatedSizePerSegment) => {
    if (segments && segments.length > 0) {
      // 如果有分片信息，累加所有分片大小
      return segments.reduce((total, segment) => total + (segment.size || 0), 0)
    }
    
    if (totalSegments && estimatedSizePerSegment) {
      // 如果知道分片数量和预估分片大小
      return totalSegments * estimatedSizePerSegment
    }
    
    return 0
  }

  // 更新下载速度（改进版本）
  const updateDownloadSpeed = (taskId, speed, timestamp = Date.now()) => {
    const speedData = {
      speed: speed,
      timestamp: timestamp
    }
    downloadSpeeds.value.set(taskId, speedData)
  }

  // 获取下载速度（改进版本）
  const getDownloadSpeed = (taskId) => {
    const speedData = downloadSpeeds.value.get(taskId)
    if (!speedData) return 0
    
    // 检查速度数据是否过期（超过5秒）
    const now = Date.now()
    if (now - speedData.timestamp > 5000) {
      downloadSpeeds.value.delete(taskId)
      return 0
    }
    
    return speedData.speed || 0
  }

  // 计算平均下载速度
  const calculateAverageSpeed = (taskId, timeWindow = 10000) => {
    const speedData = downloadSpeeds.value.get(taskId)
    if (!speedData) return 0
    
    const now = Date.now()
    if (now - speedData.timestamp > timeWindow) {
      return 0
    }
    
    return speedData.speed || 0
  }

  // 计算预估剩余时间
  const calculateRemainingTime = (taskId) => {
    const task = tasks.value.find(t => t.id === taskId)
    if (!task || task.status !== 'downloading') return 0
    
    const currentSpeed = getDownloadSpeed(taskId)
    if (!currentSpeed || currentSpeed === 0) return 0
    
    const remainingSize = (task.totalSize || 0) - (task.downloadedSize || 0)
    if (remainingSize <= 0) return 0
    
    return Math.ceil(remainingSize / currentSpeed)
  }

  // 格式化剩余时间
  const formatRemainingTime = (seconds) => {
    if (!seconds || seconds <= 0) return '计算中...'
    
    const h = Math.floor(seconds / 3600)
    const m = Math.floor((seconds % 3600) / 60)
    const s = Math.floor(seconds % 60)
    
    if (h > 0) return `${h}小时${m}分钟`
    if (m > 0) return `${m}分钟${s}秒`
    return `${s}秒`
  }

  // 创建任务
  const createTask = async (taskData) => {
    const task = {
      id: taskData.id || Date.now().toString(),
      filename: taskData.filename,
      url: taskData.url,
      outputPath: taskData.outputPath || settingsStore.getDefaultDownloadPath,
      concurrentThreads: taskData.concurrentThreads || settingsStore.getDefaultConcurrentThreads,
      retryCount: 0,
      maxRetries: taskData.maxRetries || settingsStore.getDefaultRetryCount,
      sizeCalculationMethod: taskData.sizeCalculationMethod || 'auto',
      status: 'pending',
      progress: 0,
      downloadedSize: 0,
      totalSize: 0,
      downloadedSegments: 0,
      totalSegments: 0,
      startTime: Date.now(),
      segments: [],
      failedSegments: [],
      outputFile: null,
      mergeProgress: 0,
      error: null,
      completedTime: null,
      errorTime: null
    }

    console.log('Creating new task:', task)
    // 使用展开运算符创建新数组以确保响应式更新
    tasks.value = [...tasks.value, task]
    saveTasksToStorage()

    // 如果设置了自动启动，则立即开始下载
    if (taskData.autoStart !== false) {
      try {
        await startTask(task.id)
      } catch (error) {
        console.error('Failed to auto-start task:', error)
        // 即使自动启动失败，也不影响任务创建
      }
    }

    return task
  }

  // 启动任务
  const startTask = async (taskId) => {
    const task = tasks.value.find(t => t.id === taskId)
    if (!task) {
      throw new Error('Task not found')
    }

    if (task.status !== 'pending' && task.status !== 'paused' && task.status !== 'error') {
      throw new Error('Task cannot be started in current status: ' + task.status)
    }

    try {
      if (window.electronAPI) {
        const result = await window.electronAPI.startDownload({
          taskId: task.id,
          url: task.url,
          filename: task.filename,
          outputPath: task.outputPath,
          concurrentThreads: task.concurrentThreads,
          maxRetries: task.maxRetries,
          sizeCalculationMethod: task.sizeCalculationMethod || 'auto'
        })
        
        if (result && result.success) {
          // 更新任务状态为下载中
          updateTask(taskId, { status: 'downloading' })
          console.log('Task started successfully:', taskId)
        } else {
          throw new Error(result?.error || '启动任务失败')
        }
      } else {
        // 如果没有Electron API，直接更新状态（用于开发环境）
        updateTask(taskId, { status: 'downloading' })
        console.log('Task started (development mode):', taskId)
      }
    } catch (error) {
      console.error('Failed to start task:', error)
      // 更新任务状态为错误
      updateTask(taskId, { 
        status: 'error', 
        error: error.message,
        errorTime: Date.now()
      })
      throw error
    }
  }

  // 暂停任务
  const pauseTask = async (taskId) => {
    const taskIndex = tasks.value.findIndex(t => t.id === taskId)
    const task = tasks.value[taskIndex]
    if (task && task.status === 'downloading') {
      try {
        if (window.electronAPI) {
          const result = await window.electronAPI.pauseDownload(taskId)
          if (result && result.success) {
            const updatedTask = { ...task, status: 'paused' }
            tasks.value.splice(taskIndex, 1, updatedTask)
            saveTasksToStorage()
          } else {
            throw new Error(result?.error || '暂停任务失败')
          }
        } else {
          // 如果没有Electron API，直接更新状态
          const updatedTask = { ...task, status: 'paused' }
          tasks.value.splice(taskIndex, 1, updatedTask)
          saveTasksToStorage()
        }
      } catch (error) {
        console.error('Failed to pause task:', error)
        throw error
      }
    }
  }

  // 恢复任务
  const resumeTask = async (taskId) => {
    const taskIndex = tasks.value.findIndex(t => t.id === taskId)
    const task = tasks.value[taskIndex]
    if (task && task.status === 'paused') {
      try {
        if (window.electronAPI) {
          const result = await window.electronAPI.resumeDownload(taskId)
          if (result && result.success) {
            const updatedTask = { ...task, status: 'downloading' }
            tasks.value.splice(taskIndex, 1, updatedTask)
            saveTasksToStorage()
          } else {
            throw new Error(result?.error || '恢复任务失败')
          }
        } else {
          // 如果没有Electron API，直接更新状态
          const updatedTask = { ...task, status: 'downloading' }
          tasks.value.splice(taskIndex, 1, updatedTask)
          saveTasksToStorage()
        }
      } catch (error) {
        console.error('Failed to resume task:', error)
        throw error
      }
    }
  }

  // 重试任务
  const retryTask = async (taskId) => {
    const task = tasks.value.find(t => t.id === taskId)
    if (task && task.status === 'error') {
      try {
        if (window.electronAPI) {
          await window.electronAPI.retryTask(taskId)
        }
        // 重置任务状态
        const taskIndex = tasks.value.findIndex(t => t.id === taskId)
        if (taskIndex !== -1) {
          const updatedTask = { ...tasks.value[taskIndex] }
          updatedTask.status = 'pending'
          updatedTask.progress = 0
          updatedTask.downloadedSize = 0
          updatedTask.downloadedSegments = 0
          updatedTask.retryCount = 0
          updatedTask.error = null
          updatedTask.errorTime = null
          updatedTask.startTime = Date.now()
          
          tasks.value.splice(taskIndex, 1, updatedTask)
          saveTasksToStorage()
        }
      } catch (error) {
        console.error('Failed to retry task:', error)
        throw error
      }
    }
  }

  // 删除任务
  const deleteTask = async (taskId) => {
    try {
      const index = tasks.value.findIndex(t => t.id === taskId)
      if (index > -1) {
        const task = tasks.value[index]
        
        // 调用后端删除接口
        if (window.electronAPI) {
          try {
            const result = await window.electronAPI.deleteTask(taskId)
            if (!result.success) {
              console.warn('Backend delete failed:', result.error)
              // 即使后端删除失败，也继续删除前端数据
            }
          } catch (error) {
            console.warn('Failed to call backend delete:', error)
            // 即使后端删除失败，也继续删除前端数据
          }
        }
        
        // 从前端存储中删除
        tasks.value = tasks.value.filter(t => t.id !== taskId)
        downloadSpeeds.value.delete(taskId) // 删除下载速度记录
        saveTasksToStorage()
        
        console.log('Task deleted successfully:', taskId)
        return true
      } else {
        console.warn('Task not found for deletion:', taskId)
        return false
      }
    } catch (error) {
      console.error('Failed to delete task:', error)
      throw error
    }
  }

  // 更新任务状态
  const updateTask = (taskId, updates) => {
    console.log(`=== Updating task ${taskId} ===`)
    console.log('Updates:', updates)
    
    const taskIndex = tasks.value.findIndex(t => t.id === taskId)
    if (taskIndex !== -1) {
      const task = tasks.value[taskIndex]
      const oldProgress = task.progress
      const oldStatus = task.status
      
      console.log('Current task state:', {
        id: task.id,
        status: task.status,
        progress: task.progress,
        downloadedSize: task.downloadedSize,
        totalSize: task.totalSize,
        downloadedSegments: task.downloadedSegments,
        totalSegments: task.totalSegments
      })
      
      // 创建新的任务对象以确保响应式更新
      const updatedTask = { ...task }
      
      // 应用更新
      Object.keys(updates).forEach(key => {
        if (updates[key] !== undefined) {
          updatedTask[key] = updates[key]
        }
      })
      
      // 改进的进度计算逻辑
      if (updates.progress === undefined || updates.progress === null) {
        // 优先使用分片进度
        if (updatedTask.downloadedSegments && updatedTask.totalSegments && updatedTask.totalSegments > 0) {
          updatedTask.progress = Math.floor((updatedTask.downloadedSegments / updatedTask.totalSegments) * 100)
          console.log(`Progress calculated from segments: ${oldProgress}% -> ${updatedTask.progress}%`)
        } else if (updatedTask.downloadedSize && updatedTask.totalSize && updatedTask.totalSize > 0) {
          updatedTask.progress = Math.floor((updatedTask.downloadedSize / updatedTask.totalSize) * 100)
          console.log(`Progress calculated from size: ${oldProgress}% -> ${updatedTask.progress}%`)
        } else {
          updatedTask.progress = 0
          console.log(`Progress set to 0 (no data available)`)
        }
      } else {
        console.log(`Progress from backend: ${oldProgress}% -> ${updates.progress}%`)
      }
      
      // 确保进度在有效范围内
      updatedTask.progress = Math.max(0, Math.min(100, updatedTask.progress))
      
      // 记录状态变化
      if (updates.status && updates.status !== oldStatus) {
        console.log(`Status changed: ${oldStatus} -> ${updates.status}`)
      }
      
      // 记录进度和大小信息变化
      if (updates.downloadedSize !== undefined || updates.totalSize !== undefined) {
        console.log(`Size updated: ${updatedTask.downloadedSize}/${updatedTask.totalSize} (${updatedTask.progress}%)`)
      }
      
      if (updates.downloadedSegments !== undefined || updates.totalSegments !== undefined) {
        console.log(`Segments updated: ${updatedTask.downloadedSegments}/${updatedTask.totalSegments}`)
      }
      
      console.log('Updated task state:', {
        id: updatedTask.id,
        status: updatedTask.status,
        progress: updatedTask.progress,
        downloadedSize: updatedTask.downloadedSize,
        totalSize: updatedTask.totalSize,
        downloadedSegments: updatedTask.downloadedSegments,
        totalSegments: updatedTask.totalSegments
      })
      
      // 使用Vue的响应式数组更新方法
      tasks.value.splice(taskIndex, 1, updatedTask)
      
      // 强制触发响应式更新
      tasks.value = [...tasks.value]
      
      console.log(`Task ${taskId} updated successfully. Total tasks: ${tasks.value.length}`)
      saveTasksToStorage()
    } else {
      console.warn('Task not found for update:', taskId)
      console.log('Available task IDs:', tasks.value.map(t => t.id))
    }
  }

  // 设置当前任务
  const setCurrentTask = (taskId) => {
    currentTask.value = tasks.value.find(t => t.id === taskId) || null
  }

  // 清理已完成的任务
  const cleanupCompletedTasks = (maxAge = 7 * 24 * 60 * 60 * 1000) => { // 默认7天
    const now = Date.now()
    const cutoff = now - maxAge
    
    const filteredTasks = tasks.value.filter(task => {
      if (task.status === 'completed' && task.startTime < cutoff) {
        downloadSpeeds.value.delete(task.id) // 删除下载速度记录
        return false
      }
      return true
    })
    
    tasks.value = filteredTasks
    saveTasksToStorage()
  }

  // 获取任务统计信息
  const getTaskStats = () => {
    const stats = {
      total: tasks.value.length,
      active: activeTasks.value.length,
      completed: completedTasks.value.length,
      failed: failedTasks.value.length,
      paused: pausedTasks.value.length,
      pending: pendingTasks.value.length
    }
    
    return stats
  }

  // 初始化事件监听
  const initializeEventListeners = () => {
    console.log('Checking for Electron API availability...')
    console.log('window.electronAPI:', window.electronAPI)
    
    if (!window.electronAPI) {
      console.warn('Electron API not available, skipping event listener initialization')
      return false
    }

    console.log('Setting up event listeners...')

    try {
      // 先移除可能存在的旧监听器
      window.electronAPI.removeAllListeners('download-progress')
      window.electronAPI.removeAllListeners('download-completed')
      window.electronAPI.removeAllListeners('download-error')
      
      window.electronAPI.onDownloadProgress((event, data) => {
        console.log('=== Received download progress event ===')
        console.log('Task ID:', data.taskId)
        console.log('Raw data:', data)
        
        // 计算总文件大小（改进版本）
        let calculatedTotalSize = data.totalSize
        if (!calculatedTotalSize || calculatedTotalSize === 0) {
          if (data.segments && Array.isArray(data.segments) && data.segments.length > 0) {
            // 如果有分片信息，累加所有分片大小
            calculatedTotalSize = data.segments.reduce((total, segment) => {
              const segmentSize = segment.size || segment.length || 0
              return total + segmentSize
            }, 0)
            console.log('Calculated total size from segments:', calculatedTotalSize)
          } else if (data.totalSegments && data.totalSegments > 0) {
            // 如果知道分片数量，使用预估大小
            const estimatedSizePerSegment = 1024 * 1024 // 1MB per segment (保守估计)
            calculatedTotalSize = data.totalSegments * estimatedSizePerSegment
            console.log('Estimated total size from segments count:', calculatedTotalSize)
          }
        }
        
        // 计算进度（改进版本）
        let calculatedProgress = data.progress
        if (calculatedProgress === undefined || calculatedProgress === null) {
          // 优先使用分片进度
          if (data.downloadedSegments && data.totalSegments && data.totalSegments > 0) {
            calculatedProgress = Math.floor((data.downloadedSegments / data.totalSegments) * 100)
            console.log('Progress calculated from segments:', calculatedProgress + '%')
          } else if (data.downloadedSize && calculatedTotalSize && calculatedTotalSize > 0) {
            calculatedProgress = Math.floor((data.downloadedSize / calculatedTotalSize) * 100)
            console.log('Progress calculated from size:', calculatedProgress + '%')
          } else {
            calculatedProgress = 0
          }
        }
        
        // 确保进度在有效范围内
        calculatedProgress = Math.max(0, Math.min(100, calculatedProgress))
        
        // 更新任务状态
        const updateData = {
          status: data.status,
          progress: calculatedProgress,
          downloadedSize: data.downloadedSize || 0,
          totalSize: calculatedTotalSize || 0,
          downloadedSegments: data.downloadedSegments || 0,
          totalSegments: data.totalSegments || 0,
          mergeProgress: data.mergeProgress || 0,
          failedSegments: data.failedSegments || [],
          segments: data.segments || []
        }
        
        console.log('Updating task with data:', updateData)
        console.log('Task progress details:', {
          progress: calculatedProgress + '%',
          downloadedSize: data.downloadedSize || 0,
          totalSize: calculatedTotalSize || 0,
          downloadedSegments: data.downloadedSegments || 0,
          totalSegments: data.totalSegments || 0
        })
        
        // 立即更新任务状态
        updateTask(data.taskId, updateData)
        
        // 强制触发响应式更新
        setTimeout(() => {
          const taskIndex = tasks.value.findIndex(t => t.id === data.taskId)
          if (taskIndex !== -1) {
            const currentTask = tasks.value[taskIndex]
            if (currentTask.progress !== calculatedProgress) {
              console.log(`Forcing progress update: ${currentTask.progress}% -> ${calculatedProgress}%`)
              const updatedTask = { ...currentTask, progress: calculatedProgress }
              tasks.value.splice(taskIndex, 1, updatedTask)
              
              // 强制触发响应式更新
              tasks.value = [...tasks.value]
            }
          }
        }, 0)

        // 更新下载速度
        if (data.downloadSpeed !== undefined) {
          updateDownloadSpeed(data.taskId, data.downloadSpeed, Date.now())
        }
        
        console.log('=== Progress update completed ===')
      })

      window.electronAPI.onDownloadCompleted((event, data) => {
        console.log('Received download completed event:', data)
        updateTask(data.taskId, {
          status: 'completed',
          progress: 100,
          outputFile: data.outputFile,
          completedTime: Date.now()
        })
        
        // 清除下载速度记录
        downloadSpeeds.value.delete(data.taskId)
      })

      window.electronAPI.onDownloadError((event, data) => {
        console.log('Received download error event:', data)
        updateTask(data.taskId, {
          status: 'error',
          error: data.error,
          errorTime: Date.now()
        })
        
        // 清除下载速度记录
        downloadSpeeds.value.delete(data.taskId)
      })

      console.log('Event listeners set up successfully')
      return true
    } catch (error) {
      console.error('Failed to set up event listeners:', error)
      return false
    }
  }

  // 同步后端任务状态
  const syncBackendTasks = async () => {
    try {
      if (window.electronAPI && window.electronAPI.getTaskList) {
        const result = await window.electronAPI.getTaskList()
        if (result.success && result.data) {
          console.log('Syncing backend tasks:', result.data.length)
          
          // 更新前端任务状态
          for (const backendTask of result.data) {
            const existingTask = tasks.value.find(t => t.id === backendTask.id)
            if (existingTask) {
              // 更新现有任务状态
              const taskIndex = tasks.value.findIndex(t => t.id === backendTask.id)
              const updatedTask = { ...existingTask, ...backendTask }
              
              // 特殊处理：如果后端任务状态是pending，确保前端也显示为pending
              if (backendTask.status === 'pending') {
                updatedTask.status = 'pending'
                console.log(`Task ${backendTask.id} synced as pending`)
              }
              
              tasks.value.splice(taskIndex, 1, updatedTask)
            } else {
              // 添加新的后端任务
              tasks.value = [...tasks.value, backendTask]
            }
          }
          
          saveTasksToStorage()
          console.log('Backend tasks synced successfully')
        }
      }
    } catch (error) {
      console.error('Failed to sync backend tasks:', error)
    }
  }

  // 初始化
  const initialize = async () => {
    console.log('Initializing task store...')
    loadTasksFromStorage()
    const listenersSet = initializeEventListeners()
    
    // 同步后端任务状态
    await syncBackendTasks()
    
    console.log('Task store initialization completed. Event listeners set:', listenersSet)
  }

  return {
    tasks,
    currentTask,
    activeTasks,
    completedTasks,
    failedTasks,
    pausedTasks,
    pendingTasks,
    createTask,
    startTask,
    pauseTask,
    resumeTask,
    retryTask,
    deleteTask,
    updateTask,
    setCurrentTask,
    cleanupCompletedTasks,
    getTaskStats,
    formatFileSize,
    formatDownloadSpeed,
    getDownloadSpeed,
    calculateRemainingTime,
    formatRemainingTime,
    initialize
  }
}) 